import { Button, Select, message } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';

import {
  getDataQueryList,
  getCheckPointAll,
  exportDataQuery,
  getMaterialMainDataListAll,
} from '@/services';
import moment from 'moment';
import { downloadFile } from '@/utils/utils';

const today = [
  moment(`${moment().format('YYYY-MM-DD')} 00:00:00`),
  moment(`${moment().format('YYYY-MM-DD')} 23:59:59`),
];
const DataQuery = () => {
  const intl = useIntl();
  const actionRef = useRef(null);
  const [allCheckPointList, setAllCheckPointList] = useState([]);
  const [materialCodeList, setMaterialCodeList] = useState([]);

  const [queryParams, setQueryParams] = useState();
  const [exportLoading, setExportLoading] = useState(false);

  const queryCheckPointAll = async () => {
    const res = await getCheckPointAll();
    if (res.data && res.data.length) {
      setAllCheckPointList(res.data);
    }
  };

  const queryMaterialCodeAll = async () => {
    const res = await getMaterialMainDataListAll();
    if (res.data && res.data.length) {
      setMaterialCodeList(res.data);
    }
  };

  const handleExport = async () => {
    setExportLoading(true);
    const res = await exportDataQuery(queryParams);
    if (res.code === 0) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      downloadFile(res.msg);
    }
    setExportLoading(false);
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.dataQuery.checkPoint" defaultMessage="检测点" />,
      dataIndex: 'deviceLocation',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <Select
            showSearch={true}
            optionFilterProp="children"
            onFocus={allCheckPointList.length === 0 && queryCheckPointAll}
          >
            {allCheckPointList.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.location}
              </Select.Option>
            ))}
          </Select>
        );
      },
    },

    {
      title: <FormattedMessage id="pages.dataQuery.materialCode" defaultMessage="物料编码" />,
      dataIndex: 'materialCode',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.materialName" defaultMessage="物料名称" />,
      dataIndex: 'materialName',
      ellipsis: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <Select
            showSearch={true}
            optionFilterProp="children"
            onFocus={materialCodeList.length === 0 && queryMaterialCodeAll}
          >
            {materialCodeList.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.materialDesc}
              </Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.dataQuery.project" defaultMessage="检测项目" />,
      dataIndex: 'inspectionName',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.max" defaultMessage="最大值" />,
      dataIndex: 'max',
      search: false,
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.min" defaultMessage="最小值" />,
      dataIndex: 'min',
      search: false,
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.checkNumber" defaultMessage="检测值" />,
      dataIndex: 'inspectionValue',
      search: false,
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.dataQuery.checkTime" defaultMessage="检测时间" />,
      dataIndex: 'createTime',
      valueType: 'dateTimeRange',
      render: (_, record) => {
        return moment(record.createTime).format('YYYY-MM-DD HH:mm:ss');
      },
    },
  ];

  const queryList = async (params) => {
    const startTime = params.createTime
      ? moment(params.createTime[0]).format('YYYY-MM-DD HH:mm:ss')
      : moment(today[0]).format('YYYY-MM-DD HH:mm:ss');
    const endTime = params.createTime
      ? moment(params.createTime[1]).format('YYYY-MM-DD HH:mm:ss')
      : moment(today[1]).format('YYYY-MM-DD HH:mm:ss');
    const query = {
      ...params,
      pageNum: params.current,
      startTime,
      endTime,
      deviceId: params.deviceLocation,
      materialId: params.materialName,
    };
    delete query.deviceLocation;
    delete query.materialName;
    delete query.createTime;

    setQueryParams(query);
    const res = await getDataQueryList(query);
    if (res) {
      return res;
    }
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 80,
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
          <Button loading={exportLoading} key="export" type="primary" onClick={handleExport}>
            <FormattedMessage id="pages.export" defaultMessage="导出" />
          </Button>,
        ]}
        request={(params, sorter, filter) => queryList({ ...params })}
        columns={columns}
      />
    </PageContainer>
  );
};

export default DataQuery;
